package cn.edu.njuit.server.ugcnote.ugcnoteserver.apis;

import cn.edu.njuit.server.ugcnote.ugcnoteserver.entity.NoteInfo;
import cn.edu.njuit.server.ugcnote.ugcnoteserver.entity.UserInfo;
import cn.edu.njuit.server.ugcnote.ugcnoteserver.service.AccountService;
import cn.edu.njuit.server.ugcnote.ugcnoteserver.service.NoteInfoService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class UserNoteApi {
    private final AccountService accountService;
    private final NoteInfoService noteInfoService;

    public UserNoteApi(AccountService accountService, NoteInfoService noteInfoService) {
        this.accountService = accountService;
        this.noteInfoService = noteInfoService;
    }

    @GetMapping("/note/mine")
    public ResponseEntity getMyNotes(){
        Authentication user=SecurityContextHolder.getContext().getAuthentication();
        User currentUser=(User)user.getPrincipal();
        JSONObject result = new JSONObject();
        result.put("info","这是我的笔记列表API");
        return ResponseEntity.ok(result);
    }

    @PostMapping("/note/publish")
    public ResponseEntity publishNote(@RequestBody NoteInfo note){
        try{
            Authentication user=SecurityContextHolder.getContext().getAuthentication();
            User currentUser=(User)user.getPrincipal();
            UserInfo userInfo=this.accountService.getUser(currentUser.getUsername());
            if(userInfo!=null){
                note.setUserInfo(userInfo);
                note=this.noteInfoService.publishNote(note);
                return ResponseEntity.ok(note);
            }else{
                JSONObject error = new JSONObject();
                error.put("error","登录身份不合法");
                return ResponseEntity.status(400).body(error);
            }
        }catch(Exception e){
            JSONObject error = new JSONObject();
            error.put("error",e.getMessage());
            return ResponseEntity.status(400).body(error);
        }

    }


}
